package com.example.day01.book;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.example.day01.R;

public class BookSpActivity extends AppCompatActivity {
    Spinner sp1,sp2;
    //    数据源
    String books[] = {"三国演义","西游记","水浒传","红楼梦","聊斋志异"};
    String name[][] = {{"诸葛亮","刘备","关羽","张飞"},{"唐僧","孙悟空","猪八戒","沙和尚"},
            {"宋江","武松","鲁智深","时迁","吴用"},{"贾宝玉","林黛玉","薛宝钗","王熙凤"},
            {"聂小倩","宁采臣","燕赤霞","黑山老妖"}};
    private ArrayAdapter<String> bookAdapter;
    private ArrayAdapter<String> nameAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_sp);
        sp1 = findViewById(R.id.book_sp1);
        sp2 = findViewById(R.id.book_sp2);
//      创建适配器对象  1.当前的activity类  2.代表每一个条目对应的布局   3.代表改变的文本对应的控件的id   4.数据源
        bookAdapter = new ArrayAdapter<>(this, R.layout.item_booksp, R.id.item_booksp_tv, books);
//        设置适配器
        sp1.setAdapter(bookAdapter);

//        创建二级下拉列表对应的适配器对象
        nameAdapter = new ArrayAdapter<>(this, R.layout.item_booksp, R.id.item_booksp_tv);
//        设置适配器
        sp2.setAdapter(nameAdapter);

//        设置spinner的监听器
        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                position :表示被选中的位置
                String[] arr = name[position];
                nameAdapter.clear();
                nameAdapter.addAll(arr);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}